package com.jml.executor;

import com.jml.annotation.Select;
import com.jml.statement.MappedStatement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public abstract class BaseExecutor {
    //key是sql和参数和返回值的拼接
    private Map<String, Object> cache = new HashMap<String, Object>();

    public <T> T executor(MappedStatement mappedStatement) {
        if (mappedStatement.getSqlType() instanceof Select) {
            query(mappedStatement);
        }
        return null;
    }

    public <E> List<E> query(MappedStatement ms) {
        //先查询一级缓存
        List<E> listValue = (List<E>) cache.get(ms.getMappedStatementKey());
        if (listValue != null) {
            return listValue;
        }
        // 调用数据库查询
        return queryFromDatabase(ms);
    }

    private <E> List<E> queryFromDatabase(MappedStatement ms) {
        System.out.println("调用数据查询...ms:"+ms.toString());
        List<E> list = doQuery(ms);
        if (list != null) {
            //添加一级缓存
            cache.put(ms.getMappedStatementKey(), list);
        }
        return list;
    }

    protected abstract <E> List<E> doQuery(MappedStatement ms);
}
